<template>
  <div class="user_admin_box">
    <el-dialog
      @close="handleClose(false)"
      @open="handleOpen"
      close-on-press-escape
      v-dialogDrag
      :title="isedit ? '编辑用户' : '添加用户'"
      :close-on-click-modal="false"
      :lock-scroll="false"
      :visible="showDialog"
      width="650px"
    >
      <el-form
        label-position="right"
        :model="form"
        :rules="rules"
        ref="formRef"
        size="mini"
        class="demo-ruleForm"
        label-width="auto"
      >
        <el-row :gutter="16" type="flex">
          <el-col :span="24">
            <el-form-item label="用户名:" prop="username">
              <el-input
                :disabled="isedit"
                v-model="form.username"
                placeholder="请输入"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="性别:" prop="sex">
              <el-radio-group v-model="form.sex">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="选择租户:" prop="tenantCloneIds">
              <el-select
                clearable
                size="small"
                class="w100"
                v-model="form.tenantCloneIds"
                multiple
                placeholder="请选择"
              >
                <el-option
                  v-for="item in tenantidList"
                  :key="item.id"
                  :label="item.token"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="选择部门:" prop="deptId">
              <el-cascader
                :popper-class="
                  !depList.length ? 'user_admin_cascader_nodata' : ''
                "
                clearable
                class="w100"
                v-model="form.deptId"
                :options="depList"
                :props="{
                  checkStrictly: true, //单选任意一级
                  expandTrigger: 'hover',
                  value: 'id',
                  label: 'name',
                }"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="手机:" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入"> </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="邮箱:" prop="email">
              <el-input v-model="form.email" placeholder="请输入"> </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="密码:" prop="password">
              <el-input
                show-password
                :disabled="isedit"
                v-model="form.password"
                placeholder="请输入"
                type="password"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="图片:" prop="imageUrl">
              <div style="display: flex">
                <app-upload
                  style="width: 100px; heigh: 100px; margin-right: 10px"
                  tips=""
                  :is-resolution="true"
                  @subUploadSucceed="handleUploadSucceed"
                  :isTenant="false"
                />
                <div class="imageHome" v-if="form.url">
                  <img :src="form.url | filtersFileUrl()" class="image-size" />
                </div>
                <!-- <div class="imageHome" v-else>
                  <img
                    src="http://223.223.176.32:30711/model/user_img_url.png"
                    class="image-size"
                  />
                </div> -->
              </div>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="备注:" prop="remark">
              <el-input
                type="textarea"
                v-model="form.remark"
                :rows="5"
                placeholder="请输入"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <div v-if="isedit">
          <el-button size="mini" @click="handleClose(false)">取 消</el-button>
          <el-button
            key="1"
            v-permission="[3, 'button']"
            size="mini"
            type="primary"
            :loading="btnLoadin"
            @click="submitForm('formRef')"
            >确 定</el-button
          >
        </div>
        <div v-else>
          <el-button size="mini" @click="handleClose(false)">取 消</el-button>
          <el-button
            key="2"
            v-permission="[1, 'button']"
            size="mini"
            type="primary"
            :loading="btnLoadin"
            @click="submitForm('formRef')"
            >确 定</el-button
          >
        </div>
      </div>
      <!-- <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="handleClose(false)">取 消</el-button>
        <el-button
          v-permission="[3, 'button']"
          size="mini"
          type="primary"
          @click="submitForm('formRef')"
          :loading="btnLoadin"
          >确 定</el-button
        >
      </div> -->
    </el-dialog>
  </div>
</template>

<script>
import { addUser, updateUser, getAllTenant } from "@/api/userAuth";

import AppUpload from "@/views/device/devicegroups/UploadImage.vue";
import { getDeptList } from "@/api/department";
export default {
  props: {
    isedit: {
      type: Boolean,
      default: false,
    },
    showDialog: {
      type: Boolean,
      default: false,
    },
  },
  components: {
    AppUpload,
  },
  computed: {},
  data() {
    return {
      depList: [],
      tenantidList: [],
      rules: {
        username: [
          { required: true, message: "请输入用户名" },
          {
            min: 2,
            max: 30,
            message: "用户名长度在 2 到 30 个字符",
          },
        ],
        tenantCloneIds: [
          { required: true, message: "请选择租户", trigger: "change" },
        ],
        email: [
          { required: false, message: "请输入邮箱", trigger: "change" },
          {
            pattern:
              /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
            message: "请输入正确的邮箱格式",
          },
        ],
        phone: [
          { required: true, message: "请输入手机号" },
          {
            pattern: /^(?:(?:\+|00)86)?1\d{10}$/,
            message: "请输入正确的手机号格式",
          },
        ],
        password: [
          { required: true, message: "请输入密码" },
          {
            min: 3,
            max: 12,
            message: "密码长度在 6 到 25 个字符",
          },
        ],
      },
      form: {
        url: "",
        password: "",
        email: "",
        username: "",
        phone: "",
        remark: "",
        sex: Number,
        tenantIds: "",
        tenantCloneIds: [],
        deptId: [],
      },
      btnLoadin: false,
    };
  },
  mounted() {
    this.getDepList();
    getAllTenant().then((res) => {
      this.tenantidList = res.data.data;
    });
  },
  computed: {},
  watch: {},
  methods: {
    getDepList() {
      getDeptList({ name: "" }).then((res) => {
        const { data } = res.data;
        this.depList = data ? data : [];
      });
    },
    handleUploadSucceed(url) {
      this.form.url = url;
    },
    //弹窗打开执行操作
    handleOpen() {},
    // 弹窗关闭执行操作
    handleClose(isRefresh) {
      // this.$nextTick(() => {
      this.$refs["formRef"].resetFields();
      // });
      this.$emit("update:showDialog", false);
      this.$emit("closeDialog", isRefresh);
      // 添加默认图片
    },
    //取消清空数据
    cancelEmpty() {
      this.deviceGroupForm = {};
    },
    // 提交
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          console.log("this.form :>> ", this.form);
          if (
            !this.form.tenantCloneIds ||
            this.form.tenantCloneIds.length == 0
          ) {
            this.$msg("请选择租户");
            return;
          }

          this.btnLoadin = true;
          this.form.tenantIds = this.form.tenantCloneIds.join(",");
          if (
            Object.prototype.toString.call(this.form.deptId) == "[object Array]"
          ) {
            this.form.deptId = this.form.deptId
              ? this.form.deptId[this.form.deptId.length - 1]
              : "";
          }

          if (this.isedit) {
            updateUser(this.form, this.form.tenantIds)
              .then(async (res) => {
                const isID = this.$store.state.user.user.userId == this.form.id;
                const isTenant = !this.form.tenantCloneIds.includes(
                  this.$store.state.user.tenant.tenantId
                );
                console.log("isID && isTenant :>> ", isID, isTenant);

                this.btnLoadin = false;
                this.$msg({
                  message: "编辑成功!",
                  type: "success",
                });
                if (isID && isTenant) {
                  await this.$store.dispatch("user/backtenants", true);
                  await this.$store.dispatch("tagsView/delAllViews");
                  this.$router.replace("/");
                } else {
                  this.handleClose(true);
                }
              })
              .catch((err) => {
                this.btnLoadin = false;
              });
          } else {
            await addUser(this.form, this.form.tenantIds)
              .then((res) => {
                this.btnLoadin = false;
                this.$msg({
                  message: "添加成功!",
                  type: "success",
                });
                this.handleClose(true);
              })
              .catch((err) => {
                this.btnLoadin = false;
              });
          }
        } else {
          return false;
        }
      });

      // addUser
    },
  },
};
</script>

<style lang="scss" scoped>
.user_admin_box {
  .imageHome {
    padding: 5px 5px 5px 5px;
    width: 104px;
    height: 104px;
    background: rgba(0, 0, 0, 0.04);
    border: 1px solid rgba(0, 0, 0, 0.14901960784313725);
    opacity: 1;
    border-radius: 2px;
    .image-size {
      width: 94px;
      height: 94px;
      /*background: #2E2E2E;*/
      border-radius: 50%;
      opacity: 1;
      display: flex;
    }
  }
  /deep/ .el-row--flex {
    flex-wrap: wrap;
  }
  /deep/ .el-form-item__label {
    white-space: nowrap;
  }
  /deep/ .el-tabs__nav-wrap {
    overflow: inherit;
  }
}
</style>
